package com.yonyou.gmmc.service.shopping.controller;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.MQReceiveResult;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.HandleResult;
import org.marketing.common.exception.BizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CookieSecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.infoservice.filestore.FileStore;
import com.yonyou.gmmc.common.annotation.ParamValid;
import org.marketing.common.Response;
import com.yonyou.gmmc.service.shopping.constant.ShoppingConstant;
import com.yonyou.gmmc.service.shopping.model.TmTpBalanceDetail;
import com.yonyou.gmmc.service.shopping.model.TmTpOrderInfo;
import com.yonyou.gmmc.service.shopping.model.TmTpProductDetail;
import com.yonyou.gmmc.service.shopping.model.TmTpShoppingCar;
import com.yonyou.gmmc.service.shopping.service.ShoppingOrderService;
import com.yonyou.gmmc.service.shopping.util.CookieUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商城的订单相关API
 * 
 * @author BENJAMIN
 */
@RestController
@RequestMapping(value = ShoppingConstant.BASE_PATH + "/" + ShoppingConstant.VERSION)
@Api("商城的订单相关API")
public class ShoppingOrderController {

    private Logger logger = Logger.getLogger(ShoppingOrderController.class);

    @Autowired
    private ShoppingOrderService shoppingOrderService;
    
    
    @RequestMapping(value = "/event", method = RequestMethod.POST)
    @ApiOperation(value = "接收MQ传来的关键事件", notes = "接收事件进行积分发送")
    public MQReceiveResult receiveEvent(@RequestBody BizEvent event) {
        HandleResult handleResult = shoppingOrderService.handleEvent(event);

        MQReceiveResult result = new MQReceiveResult();
        result.setMessage(handleResult.getMessage());
        result.setResult(handleResult.isHandle() ? "200" : "500");
        return result;
    }

    /**
     * 保存订单
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @return
     */
    @RequestMapping(value = "/orderInfo", method = RequestMethod.POST)
    @ApiOperation(value = "保存订单", notes = "保存订单")
    @ResponseBody
    public Response<Map<String, Object>> saveOrderInfo(@RequestBody TmTpProductDetail tmTpProductDetail,HttpServletRequest request) throws Exception {
      String openId = request.getHeader(CommonConstant.HEADER_OPENID);
      if(CheckUtil.NullOrEmpty(openId)){
      	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
      	if(!CheckUtil.NullOrEmpty(userId)){
      		openId = shoppingOrderService.selectopenIdByUserId(userId);
      	}
      }
      TmTpOrderInfo tmTpOrderInfo = new TmTpOrderInfo();
//      String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
      try {
            if(tmTpProductDetail.getRemark()!=null&&tmTpProductDetail.getRemark()!=""){
                logger.info("备注信息为："+tmTpProductDetail.getRemark());
                tmTpOrderInfo.setRemark(tmTpProductDetail.getRemark()); 
            }
            Map<String, Object> result = shoppingOrderService.saveOrderInfo(tmTpOrderInfo,openId);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        } catch (Exception e) {
            logger.error("保存状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
    
    /**
    * 查询订单
    * @author Administrator
    * TODO description
    * @date 2017年4月20日
    * @param thirdOrder
    * @param request
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/orderInfoList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取订单信息", notes = "获取订单信息")
    public Response getOrderInfoList(@RequestParam(required=false,defaultValue="") String thirdOrder
    		,@RequestParam(required=true,defaultValue="") String orderStatus //0:全部 1：代发货 2已完成
    		,HttpServletRequest request) throws Exception {
      String openId = request.getHeader(CommonConstant.HEADER_OPENID);
      if(CheckUtil.NullOrEmpty(openId)){
      	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
      	if(!CheckUtil.NullOrEmpty(userId)){
      		openId = shoppingOrderService.selectopenIdByUserId(userId);
      	}
      }
//      String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
      try {
            Map<String, Object> resultMap = shoppingOrderService.getOrderInfoList(thirdOrder,openId,orderStatus);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
        } catch (Exception e) {
            logger.error("查询状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
    /**
     * PC查询订单
     * @author lyq
     * TODO description
     * @date 2017年4月20日
     * @param thirdOrder
     * @param request
     * @return
     * @throws Exception
     */
     @RequestMapping(value = "/orderList", method = RequestMethod.GET)
     @ApiOperation(value = "获取订单信息", notes = "获取订单信息")
     public Response<PageInfo<TmTpOrderInfo>> getOrderList(
    		 @RequestParam(required=false,defaultValue="10") Integer pageNum
     		,@RequestParam(required=false,defaultValue="create_date") String sort
     		,@RequestParam(required=false,defaultValue="desc") String sortType
     		,@RequestParam(required=false,defaultValue="10") String pageSize
    		,@RequestParam(required=false,defaultValue="") String thirdOrder //订单编号
    		,@RequestParam(required=false,defaultValue="") String name //姓名
    		,@RequestParam(required=false,defaultValue="") String phone //姓名
     		,@RequestParam(required=false,defaultValue="") String orderStatus //订单状态
     		,@RequestParam(required=false,defaultValue="") String sourceType //第三方订单 10011001： 会员  10011002 ：销售顾问  10011003 ：车主
     		//,@RequestParam(required=true,defaultValue="") String logisticStatus //物流状态 0:有效 1：取消
     		,@RequestParam(required=false,defaultValue="") String startDate //开始日期
     		,@RequestParam(required=false,defaultValue="") String endDate //结束日期
     		) throws Exception {
       try {
    	   Map<String, Object> paramMap = new HashMap<String, Object>();
    	   paramMap.put("pageNum", pageNum);
    	   paramMap.put("pageSize", pageSize);
    	   paramMap.put("sort", sort);
    	   paramMap.put("sortType", sortType);
    	   paramMap.put("thirdOrder", thirdOrder);
    	   paramMap.put("name", name);
    	   paramMap.put("phone", phone);
    	   paramMap.put("orderStatus", orderStatus);
    	   paramMap.put("sourceType", sourceType);
    	   paramMap.put("startDate", startDate);
    	   paramMap.put("endDate", endDate);
    	   PageInfo<TmTpOrderInfo> resultMap = shoppingOrderService.getOrderList(paramMap);
           return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
         } catch (Exception e) {
             logger.error("查询状态发生异常",e);
             return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
         }
     }
     /**
      * PC查询订单
      * @author lyq
      * TODO description
      * @date 2017年4月20日
      * @param thirdOrder
      * @param request
      * @return
      * @throws Exception
      */
      @RequestMapping(value = "/orderListExport", method = RequestMethod.GET)
      @ApiOperation(value = "导出订单信息", notes = "导出订单信息")
      public Response<Map<String ,String>> getOrderListExport(
     		 @RequestParam(required=false,defaultValue="10") Integer pageNum
      		,@RequestParam(required=false,defaultValue="create_date") String sort
      		,@RequestParam(required=false,defaultValue="desc") String sortType
      		,@RequestParam(required=false,defaultValue="10") String pageSize
     		,@RequestParam(required=false,defaultValue="") String thirdOrder //订单编号
     		,@RequestParam(required=false,defaultValue="") String name //姓名
     		,@RequestParam(required=false,defaultValue="") String phone //姓名
      		,@RequestParam(required=false,defaultValue="") String orderStatus //订单状态
      		,@RequestParam(required=false,defaultValue="") String sourceType //第三方订单 10011001： 会员  10011002 ：销售顾问  10011003 ：车主
      		//,@RequestParam(required=true,defaultValue="") String logisticStatus //物流状态 0:有效 1：取消
      		,@RequestParam(required=false,defaultValue="") String startDate //开始日期
      		,@RequestParam(required=false,defaultValue="") String endDate //结束日期
      		) throws Exception {
    	  ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
     	   Map<String, Object> paramMap = new HashMap<String, Object>();
//     	   paramMap.put("pageNum", pageNum);
//     	   paramMap.put("pageSize", pageSize);
     	   paramMap.put("sort", sort);
     	   paramMap.put("sortType", sortType);
     	   paramMap.put("thirdOrder", thirdOrder);
     	   paramMap.put("name", name);
     	   paramMap.put("phone", phone);
     	   paramMap.put("orderStatus", orderStatus);
     	   paramMap.put("sourceType", sourceType);
     	   paramMap.put("startDate", startDate);
     	   paramMap.put("endDate", endDate);
     	   List<TmTpOrderInfo> list = shoppingOrderService.getOrderListExport(paramMap);
     	  ExportParams params = new ExportParams("订单列表","订单信息",ExcelType.XSSF);
          Workbook book = ExcelExportUtil.exportExcel(params, TmTpOrderInfo.class, list);
          book.write(os);  
          String fileName = FileStore.getInstance().write("nd02", "fs01", "orderList.xlsx", os.toByteArray());
          
          Map<String,String> fileResult = new HashMap<String,String>();
          fileResult.put("fileName","orderList.xlsx" );
          fileResult.put("url", FileStore.getInstance().getDomainURL(fileName));
     	   
     	   return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, fileResult, "");
          } catch (Exception e) {
              logger.error("查询状态发生异常",e);
              return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
          }finally {
              os.close();  
  		  }
      }
      /**
       * PC查询订单详情
       * @author lyq
       * TODO description
       * @date 2017年4月20日
       * @param thirdOrder
       * @param request
       * @return
       * @throws Exception
       */
       @RequestMapping(value = "/getOrderInfo", method = RequestMethod.GET)
       @ApiOperation(value = "PC订单详情信息查询", notes = "PC订单详情信息查询")
       public Response<Map<String ,Object>> getOrderInfo(
      		@RequestParam(required=false,defaultValue="") String thirdOrder //订单编号
       		) throws Exception {
         try {
      	   Map<String, Object> paramMap = new HashMap<String, Object>();
      	   paramMap.put("thirdOrder", thirdOrder);
      	   Map<String ,Object> list = shoppingOrderService.getOrderInfo(paramMap);
      	   return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
           } catch (Exception e) {
               logger.error("查询状态发生异常",e);
               return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
           }
    }
    /**
     * 保存购物车信息
     * 
     * @author QianKun
     * @date 2017年4月17日
     * @param tmTpShoppingCar
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/shoppingCar", method = RequestMethod.POST)
    @ApiOperation(value = "保存购物车信息", notes = "保存购物车信息")
    @ParamValid
    public Response saveShoppingCar(@RequestBody TmTpShoppingCar tmTpShoppingCar,HttpServletRequest request) throws Exception {
        String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        if(CheckUtil.NullOrEmpty(openId)){
        	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		openId = shoppingOrderService.selectopenIdByUserId(userId);
        	}
        }
        //String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
        try {
            Map<String, Object> result = shoppingOrderService.saveShoppingCar(tmTpShoppingCar,openId);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        } catch (Exception e) {
            logger.error("保存状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }

    /**
     * 查询购物车信息
     * 
     * @author QianKun
     * @date 2017年4月17日
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/shoppingCarList", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "获取购物车信息", notes = "获取购物车信息")
    public Response getShoppingCarDetail(HttpServletRequest request) throws Exception {
      String openId = request.getHeader(CommonConstant.HEADER_OPENID);
      if(CheckUtil.NullOrEmpty(openId)){
      	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
      	if(!CheckUtil.NullOrEmpty(userId)){
      		openId = shoppingOrderService.selectopenIdByUserId(userId);
      	}
      }
      //String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
      try {
            Map<String, Object> resultMap = shoppingOrderService.getShoppingCarDetail(openId);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
        } catch (Exception e) {
            logger.error("查询状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
    
    /**
     * 查询购物车总价和总数
     * 
     * @author lyq
     * @date 2017年5月5日
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/carSumPriceNum", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "查询购物车总价和总数", notes = "查询购物车总价和总数")
    public Response getCarSumPriceNum(HttpServletRequest request) throws Exception {
      String openId = request.getHeader(CommonConstant.HEADER_OPENID);
      if(CheckUtil.NullOrEmpty(openId)){
      	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
      	if(!CheckUtil.NullOrEmpty(userId)){
      		openId = shoppingOrderService.selectopenIdByUserId(userId);
      	}
      }
      //String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
      //String openId = "oXrcfuCpMJXvTH9L38ajQmEuaoxw";
      try {
            Map<String, Object> resultMap = shoppingOrderService.getCarSumPriceNum(openId);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
        } catch (Exception e) {
            logger.error("查询状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }

    /**
    * 删除购物车信息
    * @author QianKun
    * @date 2017年4月17日
    * @param userId
    * @param skuId
    * @return
    * @throws Exception
    */
    @RequestMapping(value = "/shoppingCarDelete", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "删除购物车信息", notes = "删除购物车信息")
    public Response deleteShoppingCar(@RequestBody TmTpShoppingCar tmTpShoppingCar,HttpServletRequest request) throws Exception {
      String openId = request.getHeader(CommonConstant.HEADER_OPENID);
      if(CheckUtil.NullOrEmpty(openId)){
      	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
      	if(!CheckUtil.NullOrEmpty(userId)){
      		openId = shoppingOrderService.selectopenIdByUserId(userId);
      	}
      }
      //String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
      try {
            Map<String, Object> result = shoppingOrderService.deleteShoppingCar(tmTpShoppingCar,openId);
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        } catch (Exception e) {
            logger.error("删除状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
    
    /**
     * 获取商品列表
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @param pageSize
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsList", method = RequestMethod.GET)
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表")
    public Response<PageInfo<TmTpProductDetail>> getProductDetail(@RequestParam(required=false,defaultValue="10") Integer pageNum
    		,@RequestParam(required=false,defaultValue="create_date") String sort
    		,@RequestParam(required=false,defaultValue="desc") String sortType
    		,@RequestParam(required=false,defaultValue="10") String pageSize
    		,@RequestParam(required=false,defaultValue="")String goodsNo
    		,@RequestParam(required=false,defaultValue="")String goodsName
    		,@RequestParam(required=false,defaultValue="")Integer goodStatus //JD的上下架状态
    		,@RequestParam(required=false,defaultValue="")Integer shopStatus
    		,@RequestParam(required=false,defaultValue="")Integer isHot
    		,@RequestParam(required=false,defaultValue="")Integer saleState //可售状态
    		,@RequestParam(required=false,defaultValue="")Integer pointsFrom
    		,@RequestParam(required=false,defaultValue="")Integer pointsTo
    		,@RequestParam(required=false,defaultValue="")String onDate
    		,@RequestParam(required=false,defaultValue="")Integer useType//接口使用类型 （目前“我的兑换”要传值0 ） ，其他调用暂不需要
    		,@RequestParam(required=false,defaultValue="")String category
    		,HttpServletRequest request,HttpServletResponse response) throws Exception {
       try {
//           Thread.sleep(15000);
           List<String> list2 = new ArrayList<String>();
    	   String openId = request.getHeader(CommonConstant.HEADER_OPENID);
           if(CheckUtil.NullOrEmpty(openId)){
           	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
           	if(!CheckUtil.NullOrEmpty(userId)){
           		openId = shoppingOrderService.selectopenIdByUserId(userId);
           	}
           }
//    	   String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
//    	   String SKU = CookieUtil.getCookiesByKey(request, "SKU");
//    	   logger.info("缓存中的SKU为："+SKU);
//    	   if(SKU!=null){
//    	       if(SKU.indexOf("(")>=0){
//                   Cookie skucookies = new Cookie("SKU",CookieSecurityUtil.encrypt(""));
//                   skucookies.setPath(request.getContextPath());
////                   cookies.setDomain("i-club.gmmc.com.cn");
//                   response.addCookie(skucookies);
//                   list2 = null;
//               }else{
//                   //json转成list
//                   if(SKU!=null&&SKU!=""&&SKU.indexOf("(")<0&&SKU.indexOf("[")>=0){
//                       JSONArray jsonArray = JSONArray.fromObject(SKU);
//                       list2 = (List) JSONArray.toCollection(jsonArray);
//                       logger.info("从Cookie中取到无货的SKU为："+list2.size());
//                   }else{
//                       list2 = null;
//                   }
//               }
//    	   }else{
               list2 = null;
//    	   }
    	   
//    	   SKU = SKU.replaceAll(",)", ")").replaceAll("(,", "(");
    	   Map<String,Object> queryMap = new HashMap<String,Object>();
    	   queryMap.put("pageNum", pageNum);
    	   queryMap.put("pageSize", pageSize);
    	   queryMap.put("sort", sort);
    	   queryMap.put("sortType", sortType);
    	   queryMap.put("goodsNo", goodsNo);
    	   queryMap.put("goodsName", goodsName);
    	   queryMap.put("goodStatus", goodStatus);
    	   queryMap.put("isHot", isHot);
    	   queryMap.put("saleState", saleState);
    	   queryMap.put("shopStatus", shopStatus);
    	   queryMap.put("pointsFrom", pointsFrom);
    	   queryMap.put("pointsTo", pointsTo);
    	   queryMap.put("useType", useType);
    	   queryMap.put("category", category);
    	   queryMap.put("openId", openId);
//           queryMap.put("SKU", list2);
    	   
    	   //上架日期特殊处理一下
    	   String[] onDates = onDate.replaceAll(" ", "").split("/");
    	   if(onDates!=null&&onDates.length==2){
	    	   queryMap.put("onFromDate", onDates[0].trim()+" 00:00:00");
	    	   queryMap.put("onToDate", onDates[1].trim()+" 23:59:59");
    	   }
            PageInfo<TmTpProductDetail> page = shoppingOrderService.getProductDetail(queryMap,list2);
            return new Response<PageInfo<TmTpProductDetail>>(ResultMsgConstants.RESULT_CODE_SUCCESS, page, "");
        } catch (Exception e) {
            logger.error("查询状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
    
    
    /**
     * 获取商品列表
     * 
     * @author QianKun
     * @date 2017年4月14日
     * @param pageSize
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goodsExport", method = RequestMethod.GET)
    @ApiOperation(value = "获取商品列表", notes = "获取商品列表")
    public Response<Map<String,String>> goodsExport(@RequestParam(required=false,defaultValue="10") Integer pageNum
    		,@RequestParam(required=false,defaultValue="create_date") String sort
    		,@RequestParam(required=false,defaultValue="desc") String sortType
    		,@RequestParam(required=false,defaultValue="10") String pageSize
    		,@RequestParam(required=false,defaultValue="")String goodsNo
    		,@RequestParam(required=false,defaultValue="")String goodsName
    		,@RequestParam(required=false,defaultValue="")Integer goodStatus //JD的上下架状态
    		,@RequestParam(required=false,defaultValue="")Integer shopStatus
    		,@RequestParam(required=false,defaultValue="")Integer isHot
    		,@RequestParam(required=false,defaultValue="")Integer saleState //可售状态
    		,@RequestParam(required=false,defaultValue="")Integer pointsFrom
    		,@RequestParam(required=false,defaultValue="")Integer pointsTo
    		,@RequestParam(required=false,defaultValue="")String onDate
    		,@RequestParam(required=false,defaultValue="")Integer useType
    		,@RequestParam(required=false,defaultValue="")String category
    		) throws Exception {
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       try {
    	  
    	   Map<String,Object> queryMap = new HashMap<String,Object>();
//    	   queryMap.put("pageNum", pageNum);
//    	   queryMap.put("pageSize", pageSize);
    	   queryMap.put("sort", sort);
    	   queryMap.put("sortType", sortType);
    	   queryMap.put("goodsNo", goodsNo);
    	   queryMap.put("goodsName", goodsName);
    	   queryMap.put("goodStatus", goodStatus);
    	   queryMap.put("isHot", isHot);
    	   queryMap.put("saleState", saleState);
    	   queryMap.put("shopStatus", shopStatus);
    	   queryMap.put("pointsFrom", pointsFrom);
    	   queryMap.put("pointsTo", pointsTo);
    	   queryMap.put("useType", useType);
    	   queryMap.put("category", category);
    	   
    	   //上架日期特殊处理一下
    	   String[] onDates = onDate.replaceAll(" ", "").split("/");
    	   if(onDates!=null&&onDates.length==2){
	    	   queryMap.put("onFromDate", onDates[0].trim()+" 00:00:00");
	    	   queryMap.put("onToDate", onDates[1].trim()+" 23:59:59");
    	   }
    	   
            List<TmTpProductDetail> goodsList = shoppingOrderService.getProductList(queryMap);
            ExportParams params = new ExportParams("商品列表","商品信息",ExcelType.XSSF);
            Workbook book = ExcelExportUtil.exportExcel(params, TmTpProductDetail.class, goodsList);
            book.write(os);  
            String fileName = FileStore.getInstance().write("nd02", "fs01", "goodsList.xls", os.toByteArray());
            
            Map<String,String> fileResult = new HashMap<String,String>();
            fileResult.put("fileName","goodsList.xls" );
            fileResult.put("url", FileStore.getInstance().getDomainURL(fileName));
            
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, fileResult, "");
        } catch (Exception e) {
            logger.error("查询状态发生异常",e);
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }finally {
             os.close();  
		}
	}

	/**
	 * 获取商品详情
	 * 
	 * @author lyq
	 * @date 2017年4月14日
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goodsInfo", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "获取商品详情", notes = "获取商品详情")
	@ParamValid
	public Response<Map<String, Object>> getProductDetailInfo(@RequestParam String sku) {
		logger.info("ProductController.queryTypeList==>start...");
		try {
			Map<String, Object> result = shoppingOrderService.getProductDetailInfo(sku);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		} finally {
			logger.info("ProductController.queryTypeList==>end...");
		}
	}

	/**
	 * 设置商品上下架的状态
	 *
	 * @param map
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/goodsStatus", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "设置商品上下架状态", notes = "设置商品上下架状态")
	@ParamValid // 试着用下异常统一处理
	public Response goodsStatus(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		logger.info("ProductController.goodsStatus==>start...");
		try {
			String userId = request.getHeader(ShoppingConstant.HEADER_USERID);
//            logger.info("解密前的userId为："+userId);
//			userId = CookieSecurityUtil.decrypt(userId);
//			logger.info("解密后的userId为："+userId);
//			map.put("userId", userId);
			int updateCount = shoppingOrderService.updateGoodsStatus(map);
			if (updateCount != 1) {// 更新为0
				throw BizException.DB_UPDATE_RESULT_0;
			}
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		} finally {
			logger.info("ProductController.goodsStatus==>end...");
		}

	}

	/**
	 * 设置商品是否热点
	 *
	 * @param map
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/goodsIsHot", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "设置商品是否热点", notes = "设置商品是否热点")
	@ParamValid // 试着用下异常统一处理
	public Response goodsIsHot(@RequestBody Map<String, Object> map, HttpServletRequest request) {
		logger.info("ProductController.goodsStatus==>start...");
		try {
			String userId = request.getHeader(ShoppingConstant.HEADER_USERID);
//            userId = CookieSecurityUtil.decrypt(userId);
//			map.put("userId", userId);
			int updateCount = shoppingOrderService.updateGoodsIsHot(map);
			if (updateCount != 1) {// 更新为0
				throw BizException.DB_UPDATE_RESULT_0;
			}
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		} finally {
			logger.info("ProductController.goodsStatus==>end...");
		}
	}

	/**
	 * 取消未确认订单接口
	 * 
	 * @param jdOrderId
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/cancelOrder", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "取消未确认订单", notes = "取消未确认订单")
	public Response cancelOrder(@RequestParam String thirdOrder) {
		try {
			logger.info("ProductController.cancelOrder==>start...");
			List<Map<String, Object>> result = shoppingOrderService.cancelJDOrder(thirdOrder);
			logger.info("ProductController.cancelOrder==>end...");
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 商品区域购买限制查询
	 * 
	 * @author QianKun
	 * @date 2017年4月14日
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkAreaLimit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "商品区域购买限制查询", notes = "商品区域购买限制查询")
	public Response<List<Map<String, Object>>> checkAreaLimit(@RequestBody Map<String, Object> queryMap) {
		try {

			List<Map<String, Object>> list = shoppingOrderService.checkAreaLimit(queryMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 批量获取库存接口（建议订单详情页、下单使用）
	 * 
	 * @author QianKun
	 * @date 2017年4月14日
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getNewStockById", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "批量获取库存接口（建议订单详情页、下单使用）", notes = "批量获取库存接口（建议订单详情页、下单使用）")
	public Response<List<Map<String, Object>>> getNewStockById(@RequestBody Map<String, Object> queryMap) {
		try {

			List<Map<String, Object>> list = shoppingOrderService.getNewStockById(queryMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 批量获取库存接口(建议商品列表页使用)
	 * 
	 * @author QianKun
	 * @date 2017年4月14日
	 * @param pageSize
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getStockById", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "批量获取库存接口(建议商品列表页使用)", notes = "批量获取库存接口(建议商品列表页使用)")
	public Response<List<Map<String, Object>>> getStockById(@RequestBody Map<String, Object> queryMap) {
		try {

			List<Map<String, Object>> list = shoppingOrderService.getStockById(queryMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 统一余额查询接口
	 * 
	 * @param queryMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getBalance", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "统一余额查询接口", notes = "统一余额查询接口")
	public Response<List<Map<String, Object>>> getBalance(
			@RequestParam(required = false, defaultValue = "101") Integer payType) {
		try {
			Map<String, Integer> paramMap = new HashMap<String, Integer>();
			paramMap.put("payType", payType);
			List<Map<String, Object>> list = shoppingOrderService.getBalance(paramMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 用户金彩余额查询接口
	 * 
	 * @param queryMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/selectJincaiCredit", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "用户金彩余额查询接口", notes = "用户金彩余额查询接口")
	public Response<Map<String, Object>> selectJincaiCredit() {
		try {
			Map<String, Object> map = shoppingOrderService.selectJincaiCredit();
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, map, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 余额明细查询接口
	 * 
	 * @param queryMap
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getBalanceDetail", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "余额明细查询接口", notes = "余额明细查询接口")
	public Response<PageInfo<TmTpBalanceDetail>> getBalanceDetail(
			@RequestParam(required = false, defaultValue = "10") Integer pageNum,
			@RequestParam(required = false, defaultValue = "10") String pageSize,
			@RequestParam(required = false, defaultValue = "desc") String sortType,
			@RequestParam(required = false, defaultValue = "") String orderId,
			@RequestParam(required = false, defaultValue = "") String startDate // 开始日期
			, @RequestParam(required = false, defaultValue = "") String endDate // 结束日期
	) {
		try {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("pageNum", pageNum);
			paramMap.put("pageSize", pageSize);
			paramMap.put("sortType", sortType);
			paramMap.put("orderId", orderId);
			paramMap.put("startDate", startDate);
			paramMap.put("endDate", endDate);
			PageInfo<TmTpBalanceDetail> list = shoppingOrderService.getBalanceDetail(paramMap);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, list, "");
		} catch (Exception e) {
			logger.error("查询状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}
 
    
    /**
     * 余额明细导出
     * @param pageNum
     * @param pageSize
     * @param sortType
     * @param orderId
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/balanceDetailExport", method = RequestMethod.GET)
    @ApiOperation(value = "余额明细导出", notes = "余额明细导出")
    public Response<Map<String,String>> balanceDetailExport(
    		@RequestParam(required=false,defaultValue="10") Integer pageNum
            ,@RequestParam(required=false,defaultValue="10") String pageSize
            ,@RequestParam(required=false,defaultValue="desc") String sortType
            ,@RequestParam(required=false,defaultValue="") String orderId
            ,@RequestParam(required=false,defaultValue="") String startDate //开始日期
     		,@RequestParam(required=false,defaultValue="") String endDate //结束日期
    		) throws Exception {
    	
       ByteArrayOutputStream os = new ByteArrayOutputStream();
       try {
    	   
    	   Map<String, Object> paramMap = new HashMap<String, Object>();
     	   paramMap.put("sortType", sortType);
     	   paramMap.put("orderId", orderId);
     	   paramMap.put("startDate", startDate);
     	   paramMap.put("endDate", endDate);
    	   List<TmTpBalanceDetail> list = shoppingOrderService.balanceDetailExport(paramMap);
    	   
    	   ExportParams params = new ExportParams("余额明细列表","余额明细信息",ExcelType.XSSF);
           Workbook book = ExcelExportUtil.exportExcel(params, TmTpBalanceDetail.class, list);
           book.write(os);  
           String fileName = FileStore.getInstance().write("nd02", "fs01", "balanceDetailList.xlsx", os.toByteArray());
           
           Map<String,String> fileResult = new HashMap<String,String>();
           fileResult.put("fileName","balanceDetailList.xlsx" );
           fileResult.put("url", FileStore.getInstance().getDomainURL(fileName));
      	   
      	   return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, fileResult, "");
           } catch (Exception e) {
               logger.error("查询状态发生异常",e);
               return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
           }finally {
               os.close();  
   		  }
       }

    @RequestMapping(value = "/selectStockById", method = RequestMethod.GET)
    @ApiOperation(value = "查询该地区商品库存", notes = "查询该地区商品库存")
    public Response<Map<String,Object>> selectStockById(String address,HttpServletRequest request,HttpServletResponse response) throws Exception{
        String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        if(CheckUtil.NullOrEmpty(openId)){
        	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		openId = shoppingOrderService.selectopenIdByUserId(userId);
        	}
        }
//        String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
        Map<String,Object> result = new HashMap<String,Object>();
        String sku = "";
        String addr = "";
        try{
//            Thread.sleep(15000);
            //去Cookie中查询是否存在有效的SKU(该地区库存不足的)
            sku = CookieUtil.getCookiesByKey(request, "sku");
            logger.info("从Cookie中获取的SKU为>>>>>>"+sku);
//            if(!CheckUtil.NullOrEmpty(sku)){
//                //SKU(该地区库存不足的)不为空
//                logger.info("查询到Cookie中的SKU(该地区库存不足的)为>>>>>"+sku);
//            }else{
                //SKU(该地区库存不足的)为空
                addr = CookieUtil.getCookiesByKey(request, "address");
                logger.info("查询地址的Cookie为："+addr);
                if(!CheckUtil.NullOrEmpty(address)){
                    addr = address;
                }
                if(!CheckUtil.NullOrEmpty(addr)){
                    //Cookie中的地址不为空
                    //根据Cookie中的地址去查地址名称
                    result = shoppingOrderService.selectAddName(addr);
                }else{
                    //Cookie中的地址为空,去查询该用户的收货地址
                    logger.info("Cookie中的地址为空");
                    result = shoppingOrderService.selectRecAdd(openId);
//                    if(!CheckUtil.NullOrEmpty(addr)){
//                        //查询到收货地址，使用改地址去查库存
//                        logger.info("收货地址为>>>>>>>"+addr);
//                    }else{
//                        //没有查到收货地址，使用默认地址去查库存
//                        addr = "1_0_0";//默认地址北京
//                        logger.info("默认地址为>>>>>>>>"+addr);
//                    }
                }
//            }
            addr = result.get("addr").toString();
            boolean resultFlag = shoppingOrderService.selectStockById(addr,request,response);
            if(resultFlag){
                logger.info("将无货的SKU写入Cookie成功！");
//                result.put("result", "200");
//                result.put("message", "操作成功！");
            }
            return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        }catch(Exception e){
            logger.info("查询异常:"+e.getMessage());
            return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
//            result.put("result", "500");
//            result.put("message", "操作异常！");
        }
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping(value = "/address", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "修改地址", notes = "修改地址")
    public Response<Map<String,Object>> updateAddress(@RequestParam("address") String address,HttpServletRequest request,HttpServletResponse response) throws Exception{
        String addr = "";
        try{
            addr = CookieUtil.getCookiesByKey(request, "address");
            logger.info("当前Cookie中的地址为："+addr);
            Cookie cookies = new Cookie("address",CookieSecurityUtil.encrypt(address));
            cookies.setPath(request.getContextPath());
//            cookies.setDomain("i-club.gmmc.com.cn");
            response.addCookie(cookies);
            //清除Cookie中无货的SKU
            Cookie skucookies = new Cookie("SKU",CookieSecurityUtil.encrypt(""));
            skucookies.setPath(request.getContextPath());
//            cookies.setDomain("i-club.gmmc.com.cn");
            response.addCookie(skucookies);
            logger.info("调用接口查询该地商品是否有货");
            Response<Map<String ,Object>> result = selectStockById(address,request,response);
            return result;
        }catch (Exception e){
            logger.info(e.getMessage(),e);
            return new Response(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @RequestMapping(value = "/productCategory", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ApiOperation(value = "商品分类", notes = "商品分类")
    public Response<List<Map<String,Object>>> productCategory() throws Exception{
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        try{
            result = shoppingOrderService.productCategorys();
            return new Response(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
        }catch (Exception e){
            logger.info(e.getMessage(),e);
            return new Response(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
        }
    }
}
